#ifndef VIDEODECODER_H
#define VIDEODECODER_H

#include "../data/VideoFrame.h"
#include<QString>
#include<QMutex>



// FFmpeg 头文件
extern "C" {
#include <libavutil/rational.h>  // AVRational 需要完整定义
}

struct AVCodecContext;
struct AVFormatContext;
struct AVBufferRef;

class VideoDecoder
{
public:
    VideoDecoder();
    ~VideoDecoder();

    //打开视频

    bool openVideo(const QString& videoPath);

    //关闭视频
    void closeVideo();

    //解码一帧
    VideoFrame decodeFrame(bool& isEof);

    //跳转

    bool seek(int64_t positionMs);

    //获取视频信息
    int getVideoWidth() const;
    int getVideoHeight() const;
    int64_t getVideoDurationMs() const;

    double getFps()const;


    //判断是否打开
    bool isOpened() const;

    //获取错误信息
    QString getError() const;


    //获取解码器信息

    QString getDecoderInfo()const;

    //是否使用硬件解码

    bool isUsingHardwareDecoder() const;

private:
    void freeResources();
    void setError(const QString& error,int ffmpegErrCode = -1);

    //FFmpeg资源
    AVFormatContext* m_formatContext = nullptr;
    AVCodecContext* m_codecContext = nullptr;
    int m_videoStreamIndex = -1;

    AVRational m_videoTimeBase;

    //视频信息
    int m_videoWidth = 0;
    int m_videoHeight = 0;
    int64_t m_videoDurationMs = 0;
    double m_fps = 0;

    //状态
    bool m_isOpen = false;
    QString m_error;

    //线程安全
    mutable QMutex m_mutex;  // mutable 允许在 const 函数中修改


    AVBufferRef* m_hwDeviceCtx;
    enum AVPixelFormat m_hwPixelFormat;
    bool m_useHardwareDecoder;
    QString m_decoderInfo;


private:
    bool initHardwareDecoder(enum AVHWDeviceType type);

    //释放硬件资源

    void freeHardwareDecoder();

    //硬件像素格式选择回调
    static enum AVPixelFormat getHardwareFormat(AVCodecContext* ctx,
                                                const enum AVPixelFormat* pix_fmts);

};

#endif



